package dao

import (
	"errors"
	"fmt"
)

//添加记录
func (l *AdminLogin) Add() (err error) {
	sql := fmt.Sprintf("insert into `bg_user_login` set `key`='%s',`uid`=%d,`status`=%d,`login_from`=%d,`login_ip`='%s',`user_agent`='%s',`add_time`='%s'",
		l.Key, l.Uid, l.Status, l.LoginFrom, l.LoginIp, l.UserAgent, l.AddTime)
	Result, err := Db.Exec(sql)
	if err != nil {
		return
	}
	id, err := Result.LastInsertId()
	if err != nil {
		return
	}
	l.Id = id
	return
}

//根据SessionId查找登陆记录
func (l *AdminLogin) IsLogin(session_id string) (err error) {
	err = Db.QueryRow("select id,key,uid,status,login_from,login_ip,user_agent,add_time,update_time from `bg_user_login`"+
		" where `key`=? and status=1", session_id).Scan(&l.Id, &l.Key, &l.Uid, &l.Status, &l.LoginFrom, &l.LoginIp,
		&l.UserAgent, &l.AddTime, &l.UpdateTime)
	return
}

//退出登陆
func (l *AdminLogin) Logout(session_id string) (err error) {
	Result, err := Db.Exec("update `bg_user_login` set status=0 where key=?", l.Key)
	if err != nil {
		return
	}
	num, err := Result.RowsAffected()
	if err != nil || num == 0 {
		return errors.New("")
	}

	return
}
